#include "boost/uuid/uuid_generators.hpp"
#include "boost/uuid/uuid_io.hpp"
#include "Uuid.h"

using namespace SystemTool;

// Generate uuid by random
Uuid::UniqueId Uuid::GenerateByRandom()
{
	boost::uuids::random_generator rgen;

	UniqueId Id = rgen();

	return Id;
}

// Check the string's format
bool Uuid::IsFormatOk(std::string& strUuid)
{
	if (strUuid.empty())
	{
		return false;
	}

	std::string strUuidData = strUuid;

	size_t iFirstPos = strUuid.find('{');

	size_t iSecondPos = strUuid.find('}');

	if (iFirstPos != -1 || iSecondPos != -1)
	{
		// There is one { or one } or both of them, but their position is not right
		if (iFirstPos != 0 || iSecondPos != strUuid.length() - 1)
		{
			return false;
		}

		// Wipe out the { and }
		strUuidData = strUuid.substr(1, strUuid.length() - 2);
	}

	// Check the - in the string
	for (size_t index = 0; index < strUuidData.length() - 1; ++index)
	{
		char& ch = strUuidData.at(index);

		if (ch == '-')
		{
			if (index != 8
				&& index != 13
				&& index != 18
				&& index != 23)
			{
				return false;
			}
		}
	}

	strUuid = strUuidData;

	return true;
}

// Generate uuid by string,such as {01234567-89ab-cdef-0123-456789abcdef}
bool Uuid::GenerateByString(std::string strUuid, UniqueId& UuId)
{
	if (strUuid.empty())
	{
		return false;
	}

	std::string strGuid = strUuid;

	if (!IsFormatOk(strGuid))
	{
		return false;
	}

	boost::uuids::string_generator sgen;

	UuId = sgen(strGuid);

	return true;
}

// Convert uuid to string
std::string Uuid::ToString(UniqueId Id)
{
	return boost::uuids::to_string(Id);
}
